package com.wbao.dianniu.ui;

import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.AnonymousAdapter;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQaListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.AmDataChangeManager;
import com.wbao.dianniu.manager.AmDataChangeManager.IAmDataListener;
import com.wbao.dianniu.manager.QuestSearchManager;
import com.wbao.dianniu.utils.Utils;

/**
 * 
 * 问答搜索
 * 
 * @author yejianjun
 *
 */
public class AmSearchActivity extends BaseActivity implements IQaListener, IAmDataListener {

	private PullToRefreshListView mListView;
	private EditText editText;
	private ImageView searchImageView;
	private AnonymousAdapter adapter;
	private final int PAGE_COUNTS = 10;
	private QuestSearchManager manager;
	private int currentPage = 0;
	private ListView actualListView;
	private String searchContent;
	private TextView noDataTV;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_qa_search,LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		setTitleName(getResources().getString(R.string.am_search_title));
		initView();
	}
	private void initView(){
		editText = (EditText) findViewById(R.id.search_input_edittext01);
		noDataTV = (TextView) findViewById(R.id.no_data_tv);
		noDataTV.setVisibility(View.GONE);
		searchImageView = (ImageView) findViewById(R.id.search_imagebutton01);
		searchImageView.setOnClickListener(this);
		adapter = new AnonymousAdapter(this, 2);
		mListView = (PullToRefreshListView) findViewById(R.id.search_qa_listview);
		mListView.setMode(Mode.PULL_UP_TO_REFRESH);
		mListView.setOnRefreshListener(onRefreshListener);
		
		actualListView = mListView.getRefreshableView();
		registerForContextMenu(actualListView);
		actualListView.setAdapter(adapter);
		actualListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Utils.intoAmDetailActivity(AmSearchActivity.this, (QaResponse)adapter.getItem(position-1));
			}
		});
		editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH){  
					String content = editText.getText().toString().trim();
					if(TextUtils.isEmpty(content)){
						return false;
					}
					adapter.cleanData();
					searchContent =  editText.getText().toString().trim();
					currentPage = 1;
					requstData(searchContent, currentPage);
		            return true;
		        }  
		        return false;  
			}
		});
		
		manager = new QuestSearchManager(this);
		manager.addQaListener(this);
		AmDataChangeManager.getInstance().addAmChangeListener(this);
	}
	
	
	OnRefreshListener onRefreshListener = new OnRefreshListener() {
		
		@Override
		public void onRefresh() {
			//  上拉刷新 加载请求数据
			pullUpRequest();
		}
	};
	
	// 上拉刷新数据请求
	private void pullUpRequest() {
		// 没有搜索结果 或者数据为空 上拉没有效果
		currentPage++;
		requstData(searchContent, currentPage);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != manager) {
			manager.removeQaListener(this);
		}
		AmDataChangeManager.getInstance().removeAmChangeListener(this);
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.search_imagebutton01:
			Utils.hideSoftInput(AmSearchActivity.this, editText);
			String content = editText.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				return;
			}
			adapter.cleanData();
			searchContent = editText.getText().toString().trim();
			currentPage = 1;
			requstData(searchContent, currentPage);
			break;

		default:
			break;
		}
		
	}
	
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			//intent put extra
			Intent contentIntent = new Intent();
			Bundle bundle = new Bundle();
			QaResponse resp = (QaResponse) adapter.getItem(position-1);
			if(0 == resp.showAliasName){
				bundle.putString(GlobalContext.BUNDLE_REALNAME, "");
			}else{
				bundle.putString(GlobalContext.BUNDLE_REALNAME, resp.realName);
			}
			bundle.putInt(GlobalContext.BUNDLE_ISGOOD, resp.isGood);
			bundle.putString(GlobalContext.BUNDLE_CONTENT, resp.content);
			bundle.putInt(GlobalContext.BUNDLE_VISITORCOUNT, resp.visitorCount);
			bundle.putInt(GlobalContext.BUNDLE_FORWARDCOUNT, resp.forwardCount);
			bundle.putInt(GlobalContext.BUNDLE_GOODCOUNT, resp.goodCount);
			bundle.putInt(GlobalContext.BUNDLE_ANSWERCOUNT, resp.answerCount);
			bundle.putInt(GlobalContext.BUNDLE_ACCOUNTID, 	resp.accountId);
			bundle.putInt(GlobalContext.BUNDLE_QUESTID, resp.id);
			bundle.putString(GlobalContext.BUNDLE_QUESTIMGS, resp.questImgs);
			contentIntent.putExtra(GlobalContext.AM_DATA_BUNDLE, bundle);
			contentIntent.setClass(AmSearchActivity.this, AmDetailActivity.class);
			AmSearchActivity.this.startActivity(contentIntent);
			
		}
	};
	
	private void requstData(String content, int page){
		if(TextUtils.isEmpty(content)){
			return;
		}
		manager.reqData( GlobalContext.accountId,content, 2, adapter.getCount(), PAGE_COUNTS);
	}
	
	@Override
	public void onQaFailure(int errorCode, String errorMsg) {
		// TODO Auto-generated method stub
		mListView.onRefreshComplete(false,true);
	}
	@Override
	public void onQaSuccess(List<QaResponse> list) {
		// TODO Auto-generated method stub
		mListView.onRefreshComplete(false,true);
		//收到数据
		if (null != list) {
			if (0 == currentPage) {
				adapter.cleanData();
				adapter.setData(list);
			} else {
				adapter.addDataList(list);
			}
			if (0 == adapter.getCount()) {
				noDataTV.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
			} else {
				noDataTV.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
			}
			adapter.notifyDataSetChanged();
		}
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void addOneData(QaResponse addData) {
		// TODO Auto-generated method stub
		noDataTV.setVisibility(View.GONE);
		adapter.addOneQuestData(addData);
	}

	@Override
	public void removeOneData(int questId) {
		// TODO Auto-generated method stub
		adapter.removeOneData(questId);
		if (adapter.getCount() == 0) {
			noDataTV.setVisibility(View.VISIBLE);
		} else {
			noDataTV.setVisibility(View.GONE);
		}
	}

	@Override
	public void priseNotify(int questId, int isGood, int goodCounts) {
		// TODO Auto-generated method stub
		adapter.priseNotify(questId, isGood, goodCounts);
	}

	@Override
	public void replyNotify(int questId, int answerCounts) {
		// TODO Auto-generated method stub
		adapter.replyNotify(questId, answerCounts);
	}
	
}
